# -*-coding:utf-8-*-

from delegates.base import BaseDelegate
from daos.base_async import BaseRecord
from tornado.gen import coroutine, Return
from delegates.hfs.nds.users_delegate import NdsUser

SPECIFICS = {
    'percentages': [15, 9, 6],  # 商品分成比例
    'bonus_points_unit': 1,  # 一块钱积一分
    'bonus_points_multiple': 1,  # 积分倍数
    'increase_spread_bonus_points': True,  # 是否增加用户的推广积分
    'recharge_days': 90,
}


class NdsProduct(BaseRecord):
    pass


class NdsProductsDelegate(BaseDelegate):
    def check_or_set_default_percentages(self, data, default_percentages=None):
        if 'percentages' in data:
            if not isinstance(data['percentages'], list) or 3 != len(data['percentages']):
                raise Exception('percentages field must be an array with length equal to 3')
            total = 0
            for a in data['percentages']:
                if not isinstance(a, int) or (a < 0 or a > 100):
                    raise Exception('percentages: elements type in the array must be INT and in range 0~100')
                total += a
            if 100 < total:
                raise Exception('percentages: sum(%d) of percentages exceeds 100%%' % total)
        elif default_percentages is not None:
            data['percentages'] = default_percentages

    def on_pre_create(self, **kwargs):
        specifics = kwargs['specifics']
        self.check_or_set_default_percentages(specifics, default_percentages=[15, 9, 6])
        return specifics

    def on_pre_update(self, **kwargs):
        # 在这里做 specifics 中字段做检查
        specifics = kwargs['specifics']
        return specifics

    @coroutine
    def on_pre_get(self, **kwargs):
        user_specifics = yield self._get_user_specifics()
        user = NdsUser(user_specifics)
        projection = {'_id': 0}
        filter_cond = {
            '$or': [
                {'uid': self._uid},
                {'uid': user.vendor_id},  # vendor 自身其 vendor_id 为  None
            ]}
        raise Return((filter_cond, projection))

    @coroutine
    def on_pre_get_list(self, **kwargs):
        user_specifics = yield self._get_user_specifics()
        user = NdsUser(user_specifics)
        filter_cond = {
            '$or': [
                {'uid': self._uid},
                {'uid': user.vendor_id},  # vendor 自身其 vendor_id 为  None
            ]}
        if 'type' in kwargs:
            filter_cond.update(type=kwargs.pop('type'))
        raise Return((filter_cond, None))
